﻿using System;
using System.IO;
using System.Runtime.Serialization.Json;

namespace SuperSocialShare.Helper
{
    internal class JsonConverter
    {
        /// <summary>
        /// 根据提供的json串和类型获取对象
        /// </summary>
        /// <param name="json">json串</param>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public static object GetObjectFromJsonString(String jsonstring, Type type)
        {
            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] data = System.Text.Encoding.UTF8.GetBytes(jsonstring);
                    ms.Write(data, 0, data.Length);
                    return serializer.ReadObject(ms);
                }
            }
            catch
            {
                return null;
            }
        }

        public static T GetObjectFromJsonString<T>(string jsonstring) where T : new()
        {
            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] data = System.Text.Encoding.UTF8.GetBytes(jsonstring);
                    ms.Write(data, 0, data.Length);
                    return (T)serializer.ReadObject(ms);
                }
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// 将提供的对象序列化为json串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        //public static String GetJsonStringFromObject(Object obj)
        //{
        //    try
        //    {
        //        return JsonConvert.SerializeObject(obj);
        //    }
        //    catch
        //    {
        //        return null;
        //    }
        //}

        /// <summary>
        /// 将提供的对象序列化为Json串
        /// </summary>
        public static string GetJsonStringFromObject(Object obj)
        {
            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    ms.Position = 0;
                    StreamReader reader = new StreamReader(ms);
                    return reader.ReadToEnd();
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
